package com.coda.clouddisk.controller;

import com.coda.clouddisk.annotation.Loggable;
import com.coda.clouddisk.context.BaseContext;
import com.coda.clouddisk.entity.AbsObject;
import com.coda.clouddisk.entity.KesunReturn;
import com.coda.clouddisk.entity.User;
import com.coda.clouddisk.service.SuperService;
import lombok.Data;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;

@RestController
@Data
public abstract class SuperController {

    //service层访问对象
    private SuperService superService;

    //获取实体类对象
    public abstract Map<String, Object> convertData(Map<String, Object> data);

    /**
     * 添加
     *
     * @param data
     * @return
     */
    @PostMapping(value = "/add")
    @ResponseBody
    @Loggable("添加")
    public KesunReturn add(@RequestBody Map<String, Object> data) {
        Map<String, Object> obj = convertData(data);
        getUserIdMap(data);
        //添加id
        data.put("id", UUID.randomUUID().toString().substring(0, 8).replace("-", ""));
        superService.setModels(obj);
        return superService.add();
    }

    /**
     * 查找
     *
     * @param data
     * @return
     */
    @Loggable(value = "查找")
    @GetMapping("/find")
    public KesunReturn find(@RequestParam Map<String, Object> data) {
        Map<String, Object> obj = convertData(data);
        getUserIdMap(data);
        superService.setModels(obj);
        return superService.find();
    }

    /**
     * 查询所有
     */
    @GetMapping("/findAll")
    public KesunReturn findAll(@RequestParam Map<String, Object> data) {
        Map<String, Object> obj = convertData(data);
        getUserIdMap(data);
        superService.setModels(obj);
        return superService.findAll(data);
    }

    /**
     * 分页查询
     */
    @Loggable("分页查询")
    @GetMapping("/page")
    public KesunReturn page(@RequestParam Map<String, Object> data) {
        Map<String, Object> obj = convertData(data);
        getUserIdMap(data);  //设置用户id
        superService.setModels(obj);
        return superService.findByPage(data);
    }

    /**
     * 修改
     */
    @PutMapping("/edit")
    @Loggable("修改")
    public KesunReturn edit(@RequestBody Map<String, Object> data) {
        Map<String, Object> obj = convertData(data);
        getUserIdMap(data);
        superService.setModels(obj);
        return superService.edit();
    }

    /**
     * 删除
     *
     * @param data
     * @return
     */
    @DeleteMapping("/delete")
    @Loggable("删除")
    public KesunReturn delete(@RequestBody Map<String, Object> data) {
        Map<String, Object> obj = convertData(data);
        superService.setModels(obj);
        return superService.delete((ArrayList<String>) data.get("ids"));
    }

    /**
     * 设置当前用户id
     */
    public void getUserIdMap(Map<String, Object> data) {
        User user = new User();
        user.setId(BaseContext.getCurrentId());
        data.put("user", user);
    }


}
